﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Eieboom.Models;
using Eieboom.General;
using res = Sob.Resource.Controllers.Account.Account;

namespace Eieboom.Controllers
{
    [WebFilter]
    public class AccountController : Controller
    {
        //
        // GET: /Account/LogOn
        //站点配置
        GeneralConfigInfo configinfo = Eieboom.General.WebUtils.configinfo;
        
        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult Manage()
        {
            return Redirect("/BlogAdmin/Admin/Index/");
        }

        public ActionResult CheckLogin()
        {
            return View("LogInfo");
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", res.Account_Tip1);
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return  Redirect("/");
            //return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    InitiaAdmin(model.UserName);
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        /// <summary>
        /// 初始化管理员
        /// </summary>
        [NonAction]
        private void InitiaAdmin(string user)
        {
            if (user != "admin")
                return;
            if (Roles.RoleExists("Admin"))
            {
                Roles.AddUserToRole("admin", "Admin");
            }
            else
            {
                Roles.CreateRole("Admin");
                Roles.AddUserToRole("admin", "Admin");
            }
        }


        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // 在某些出错情况下，ChangePassword 将引发异常，
                // 而不是返回 false。
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", res.Account_Tip2);
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return res.Account_Tip3;

                case MembershipCreateStatus.DuplicateEmail:
                    return res.Account_Tip4;

                case MembershipCreateStatus.InvalidPassword:
                    return res.Account_Tip5;

                case MembershipCreateStatus.InvalidEmail:
                    return res.Account_Tip6;

                case MembershipCreateStatus.InvalidAnswer:
                    return res.Account_Tip7;

                case MembershipCreateStatus.InvalidQuestion:
                    return res.Account_Tip8;

                case MembershipCreateStatus.InvalidUserName:
                    return res.Account_Tip9;

                case MembershipCreateStatus.ProviderError:
                    return res.Account_Tip10;

                case MembershipCreateStatus.UserRejected:
                    return res.Account_Tip11;

                default:
                    return res.Account_Tip12;
            }
        }
        #endregion
    }
}
